const jwt = require('jsonwebtoken')
const {
    createUser,
    getUserInfo
} = require('../service/user.service')
const {
    editBasics
} = require('../service/basics.service')
const { userRegisterError, userLoginError, toKenError } = require('../constant/err.type')
const { success, text } = require("../constant");
const { JWT_SECERT } = require('../config/config.default')
let userinfo = null
class UserController {
    async register(ctx, next) {
        console.log(ctx.request)
        const { userName, password } = ctx.request.body
        // 合法性
        try {
            const res = await createUser(userName, password)
            console.log('-------res-------', res)
            await editBasics ({userId: res.id}, 'create')
            ctx.body = {
                code: 0,
                message: '用户注册成功',
                result: {
                    id: res.id,
                    userName: res.userName
                }
            }
        } catch (err) {
            console.log(err)
            ctx.body = {
                code: 0,
                message: '用户注册成功',
                result: err
            }
            ctx.app.emit('error', userRegisterError, ctx)
        }
    }
    async login(ctx, next) {
        const { userName } = ctx.request.body
        try {
            // 获取用户信息（在token的playload中，记录id user_name is_admin）
            let {password, ...res } = await getUserInfo({ userName })
            console.log('res 登陆的时候', res)
            userinfo = JSON.stringify(res)
            ctx.body = {
                code: success,
                message: text.success,
                result: {
                    token: jwt.sign(res, JWT_SECERT, {expiresIn: '10s'}),
                    refreshToken: jwt.sign(res, JWT_SECERT, {expiresIn: '1d'}),
                }
            }
        } catch (err) {
            console.error('用户登录失败', err)
            return ctx.app.emit('error', toKenError, ctx)
        }
    }
    async refreshToKen (ctx, next) {
        const { refreshToken } = ctx.request.body
        console.log('refreshToken111111111111111111111', refreshToken)
        console.log('userinfo', userinfo)
        // 检查刷新令牌是否在黑名单中或者是否过期
        if (!jwt.verify(refreshToken, JWT_SECERT)) {
            return ctx.app.emit('error', toKenError, ctx)
        }
        ctx.body = {
            code: success,
            message: text.success,
            result: {
                token: jwt.sign(userinfo, JWT_SECERT, {expiresIn: '10s'})
            }
        }
    }

    getNsrList (ctx) {
        const callback = ctx.query.callback || 'callback'
        // console.log('xxx', ctx.query)
        let returnData = {
            success: true,
            data: {
                text: 'this is a jsonp api',
                time: new Date().getTime(),
            }
        }
        // jsonp的script字符串
        const jsonpStr = `${callback}(${JSON.stringify(returnData)})`//拼接jsonp字符串
        // const jsonpStr = `console.log(this)`//拼接jsonp字符串
        // 用text/javascript，让请求支持跨域获取

        ctx.type = 'text/javascript'
        // 输出jsonp字符串
        console.log('jsonpStr', jsonpStr)
        ctx.body = jsonpStr
    }
}
module.exports = new UserController()
